package com.mrslu.signkk.util;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 卢斌
 */
@Slf4j
public class AesBuilder {

    /**
     * AES加解密工具实例缓存
     */
    private static final ConcurrentHashMap<String, AES> AES_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>(16);

    /**
     * 固定向量
     */
    private static final byte[] IV = "0000000000000000".getBytes();


    private static AES build(String secret) {
        return new AES(Mode.CBC, Padding.PKCS5Padding, secret.getBytes(StandardCharsets.UTF_8), IV);
    }


    /**
     * 懒加载获取AES对象
     *
     * @param secret    秘钥
     * @return  AES对象
     */
    public static AES get(String secret) {
        AES aes;
        if (SecretEnum.isInValue(secret)) {
            aes = AES_CONCURRENT_HASH_MAP.get(secret);
            if (aes == null) {
                aes = build(secret);
                AES_CONCURRENT_HASH_MAP.putIfAbsent(secret, aes);
            }
            return aes;
        }
        return build(secret);
    }
    
    public static AES get(SecretEnum secretEnum) {
        if (secretEnum == null) {
            return null;
        }
        return get(secretEnum.getValue());
    }
}
